package com.leon.androidcoursedesign.adapters.baseAdapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.leon.androidcoursedesign.beans.Course;
import com.leon.androidcoursedesign.beans.Note;

import java.util.List;

public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private final List<T> beans;
    private final Context context;

    public BaseAdapter(List<T> beans, Context context) {
        this.beans = beans;
        this.context = context;
    }

    /**
     * 用于RecyclerView绑定item使用
     *
     * @return  返回itemID
     */
    public abstract int setLayout();

    /**
     * 创建ViewHolder
     *
     * @return  返回BaseViewHolder
     */
    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(setLayout(), null);
        return new BaseViewHolder(view);
    }

    /**
     * 获取数据总数
     *
     * @return  返回数据总数
     */
    @Override
    public int getItemCount() {
        return beans == null ? 0 : beans.size();
    }

    /**
     * 刷新加载数据
     *
     * @param t    要加入的数据
     */
    public void append (T t) {
        this.beans.add(t);
        notifyDataSetChanged();
    }

    /**
     * 更新信息
     *
     * @param t    要更新的数据
     */
    public void replace (T t) {
        int position = 0;

        // 判断是否为Course类型
        if (t instanceof Course) {
            Course newCourse = (Course) t;
            String itemId = newCourse.itemId;

            // 找到courseId的index
            List<T> ts = this.beans;
            for (int i = 0; i < ts.size(); i++) {
                Course temp = (Course) ts.get(i);

                if (temp.itemId.equals(itemId)) {
                    position = i;
                    break;
                }
            }

            this.beans.set(position, (T) newCourse);
        } else {
            Note newNote = (Note) t;
            String itemId = newNote.itemId;

            // 找到note的index
            List<T> ts = this.beans;
            for (int i = 0; i < ts.size(); i++) {
                Note temp = (Note) ts.get(i);

                if (temp.itemId.equals(itemId)) {
                    position = i;
                    break;
                }
            }

            this.beans.set(position, (T) newNote);
        }

        notifyDataSetChanged();
    }

    /**
     * 根据position删除指定item
     *
     * @param position  索引
     */
    public void delete(int position) {
        this.beans.remove(position);
        notifyDataSetChanged();
    }
}
